package com.rose.config;

import com.rose.pojo.Admin;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//这个类要么实现接口，要么实现别的类，最后去配置文件里面去注册
// 拦截器，用来在未登录时访问受保护页面时进行拦截并抛出AccessForbiddenException
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 通过request获得session对象
        HttpSession session = request.getSession();

        // 从session域中取出Admin对象
        Admin admin = (Admin) session.getAttribute("loginAdminName");

        // 判断admin对象是否为空，若为空表示未登录，抛出异常
        if (admin == null){
            throw new AccessForbiddenException("用户未登陆");
        }

        //不会返回false ，只会直接的抛出异常，谨记此思路
        // admin对象不为空，表示已登录，放行
        return true;
    }
}
